package com.wd.tw.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wd.tw.config.AppConfig;
import com.wd.tw.domain.dto.EventQuery;
import com.wd.tw.domain.dto.request.ApiRequest;
import com.wd.tw.domain.dto.request.ImageListRequest;
import com.wd.tw.domain.dto.response.ApiResponse;
import com.wd.tw.domain.dto.response.ImageListResponse;
import com.wd.tw.utils.HttpUtils;
import com.wd.tw.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.wd.tw.constants.ApiConstant.IMG_API;
import static com.wd.tw.constants.ApiConstant.IMG_LIST;

/**
 * @className: ImageService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/3
 **/
@Service
public class ImageService {

    private final static Logger logger = LoggerFactory.getLogger(ImageService.class);

    @Resource
    TokenService tokenService;

    @Resource
    AppConfig appConfig;

    public ImageListResponse getImageList(EventQuery eventQuery) {

        String token = tokenService.getToken();

        ApiRequest<ImageListRequest> imgListParam = new ApiRequest<>();
        imgListParam.getBasic().setToken(token);

        ImageListRequest imageListRequest = new ImageListRequest();
        imageListRequest.setOffset(eventQuery.getStart_no());
        imageListRequest.setSize(eventQuery.getQry_len());
        List<Integer> channelIds = new ArrayList<>();
        imageListRequest.setChannel_ids(channelIds);
        imageListRequest.setStart_time(TimeUtils.parseTimestamp(eventQuery.getStart_time()));
        imageListRequest.setEnd_time(TimeUtils.parseTimestamp(eventQuery.getStop_time()));


        ImageListRequest.ByEvent byEvent = new ImageListRequest.ByEvent();
        List<String> envList = new ArrayList<>();
        envList.add("bed");
        byEvent.setEvent_array(envList);
        imageListRequest.setBy_event(byEvent);

        imgListParam.setData(imageListRequest);
        String post = HttpUtils.post(appConfig.getBaseApi() + IMG_LIST, imgListParam.toString());
        logger.info(IMG_LIST + "  Response:" + post);

        if (post != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            ApiResponse<ImageListResponse> apiResponse = null;
            try {
                apiResponse = objectMapper.readValue(post, new TypeReference<ApiResponse<ImageListResponse>>() {
                });
                if(apiResponse.getBasic().getCode()!=200)
                {
                    logger.info("RefreshTokenByImageApi!");
                    tokenService.refreshToken();
                    return null;
                }
                return apiResponse.getData();
            } catch (IOException e) {
                logger.info("Query Param" + imgListParam.toString());
            }
        }
        return null;

    }

    public byte[] downloadImage(String file) throws IOException {

        String token = tokenService.getToken();
        if (file.contains(" ")) {
            logger.info(file);
            logger.info("Have space!");
            file = file.replace(" ", "+");
            logger.info(file);
        }


        String urlWithParams = String.format("%s?token=%s&url=%s", IMG_API, token, file);


//        String encodedParam = URLEncoder.encode(urlWithParams, "UTF-8");

        String imageUrl = appConfig.getBaseImgApi() + urlWithParams;

        logger.info("Get Image:" + imageUrl);

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();


        // 检查响应码
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (InputStream inputStream = connection.getInputStream();
                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                return byteArrayOutputStream.toByteArray();
            }
        } else {
            logger.info("Failed to download image: " + connection.getResponseCode());
            return new byte[5];
        }
    }


}
